Skip to content

fix(worktree): never reissue a generated workspace name - #14350

Merged
brennanb2025 merged 26 commits into
mainfrom
brennanb2025/retire-generated-workspace-names
Aug 15, 2026
Merged

brennanb2025 merged 26 commits into
mainfrom
brennanb2025/retire-generated-workspace-names

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Workspaces get a random sea-creature name. When you deleted one, its name went back in the hat — so a new workspace could get the same name, land in the same folder, and open with the previous workspace's chat history behind it. Now a name Orca picked is used once and never handed out again. A name you type is still yours to reuse.

What Changed

  • Generated names are retired permanently in a new durable registry (retiredWorktreeNamesByRepo).
  • Stored per repo id, read per cwd namespace. The collision this prevents is on the path, so reads union across every repo that creates into the same workspace root. Storage stays on the stable repo id: the namespace is derived from workspaceDir, nestWorkspaces, worktreeBasePath and repo.path, and keying storage on it would orphan every affected repo's retirements the moment a user toggles any one of those — a far more common event than removing and re-adding a repo.
  • The registry is pruned with the repo, in removeProject and in removeProjectForHost once the last host's copy of the id is gone, alongside the sparse-preset deletes that already follow that convention. It is also bounded per repo, and carried through profile transfer re-keyed to the destination repo id.
  • The registry is written in main, using the name Git actually created. The create loop can advance past a requested name on collision, so recording the renderer's proposal would drift and eventually reissue names.
  • Only names Orca generated are retired. Creates carry an explicit nameWasGenerated flag, set by the desktop composer and the mobile create sheet exactly where they fall back to the suggestion. Both the "skip a retired candidate" and the "record this name as spent" steps are gated on it, and it defaults to false so CLI and automation callers behave exactly as before. This matters because the pool contains ordinary words — orca, runner, sole, emperor, permit, molly, oscar — that people type on purpose.
  • Seeded once per cwd namespace from workspace directories plus surviving agent transcript buckets, so names already spent before this change are excluded from day one rather than only going forward. The scan is shared per namespace but the merge runs for whichever repo asked, so a second repo in the same namespace is seeded too.
  • Name suggestions exclude retired names. The existing fallback already degrades to -2, -3; those variants retire too, and tier numbering can no longer rewind onto a spent variant after a deletion.
  • Desktop and mobile now share one selector (src/shared/worktree-name-suggestion.ts). Mobile previously hand-duplicated the algorithm; each platform now keeps a thin wrapper that builds its own used-set and delegates, so the two cannot drift apart again.
  • The host publishes retired names through a narrowly scoped worktree.listRetiredNames RPC. Mobile and the web client both call it per selected repo while the create sheet is open, mirroring the desktop hook without exposing the broader worktree-list surface.
  • Create is never gated on that fetch. The host skips retired candidates before doing any Git work, so a pending fetch can only cost a suggestion. Gating the button bought nothing and could disable Create for the length of a full mobile reconnect ladder.

Why

Coding-agent CLIs key prompt history and transcripts by cwd. A recycled name means a recycled path, and the new occupant silently inherits the dead workspace's conversation.

Measured on one machine: of 552 names, 187 already carried chat history and 119 of those workspaces were deleted — the name freed, the history still on disk. That is roughly a 28% chance any new workspace inherits a stranger's chat.

Two alternatives were considered and rejected:

  • Pruning the agent's history on delete. Not sound: folder workspaces share one physical path across several worktree ids (so pruning one erases siblings' history), the file lives on the execution host for SSH workspaces, the write lock guards only flushed appends so a live process re-appends after a rewrite, and transcript bucket encoding is non-bijective so deleting by encoded cwd can erase unrelated state. We do not own that schema, lock lifecycle, or set of writers.
  • A visible token (gar-a7f3). Orca reads the path leaf in several places — display name, attachment label, smart sort, and one path that derives a branch from it — so a suffix would degrade all of them plus the user's shell prompt.

Retirement fixes it with no visible change and no writes to another tool's files. The pool becomes a consumable: at the observed rate the 552 names last about a year before the first -2 appears, and expanding the list later extends that.

Linked Issue

STA-4189 — https://linear.app/stably/issue/STA-4189/fix-duplicate-worktree-naming-bug-in-claude-tui-message-history

Fixes #

Visual Proof

N/A — no UI change by design. The point of this approach over a suffix is that suggested names look exactly as they do today; only which name is offered changes.

Testing

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • src/main/worktree-name-retirement.test.ts — the seed scan against a fake home with buckets written using the real per-character encoding, covering plain POSIX, a dot-directory root, a C:\ drive root, and a \\wsl$\ UNC root. The three platform cases fail against the encoder this PR replaces, which is how the gap below was found. Plus leaf extraction, sibling-prefix rejection, cross-repo sharing within one namespace, and a test that a repo holding no retirements never costs a path probe (which for a WSL repo is a blocking wsl.exe call).

  • src/main/ai-vault/claude-project-dir-encoding.test.ts — direct tests for the shared encoder and its scope-boundary matcher.

  • src/main/persistence-worktree-name-retirement.test.ts — per-repo scoping, case/whitespace normalization, defensive copy, merge semantics, survives reload, degrades to empty on a corrupt map, drops the registry on repo removal (and keeps it while another host row survives), and enforces the per-repo bound.

  • src/main/orca-profiles/profile-project-transfer.test.ts — retirements follow a project into another profile under the new repo id. Verified non-vacuous: removing the re-key fails it.

  • Create-path provenance is pinned at every hop: the RPC arg mapping (worktree-create-args.test.ts), the local and SSH host paths (worktrees-windows.test.ts, worktrees.test.ts), the runtime path (orca-runtime.test.ts), the desktop store slice and background create flow, and the mobile create payload. Each asserts both directions — a generated name is skipped and retired, a user-typed one is neither.

  • src/shared/worktree-name-suggestion.test.ts — the shared core: tier degradation, no rewind onto a spent variant, tier advance. Anchored on absence from the used set rather than pool position, so they cannot silently pass against a filtered pool.

  • src/renderer/.../worktree-name-suggestions.test.ts and mobile/src/components/worktree-name-suggestion.test.ts — a retired name is never reissued on either platform, layered on top of the existing cross-repo live dedup.

Verified locally: pnpm typecheck clean on all three desktop projects and on mobile; oxlint clean on every changed file; 4,448 tests pass under the root config across the retirement, persistence, worktree, runtime, RPC, and renderer suites, and all 3,461 mobile tests pass.

Note on the excluded lockfile change: mobile's toolchain was non-functional in my worktree before this work — mobile/node_modules was incomplete, so tsc and vitest both failed on pre-existing files. I ran pnpm install --frozen-lockfile inside mobile/ to get a real signal. The resulting mobile/pnpm-lock.yaml churn is not included here. It is not purely registry metadata: it also contains resolved transitive pin drift (@babel/* 7.29.7 → 7.29.8, @types/node 26.1.1 → 26.1.2). It is harmless — the install set is unchanged in both directions, with zero integrity, resolution, or package-entry changes — but it is unrelated to this PR.

Platforms: developed and tested on macOS. Path handling is separator-agnostic (native, WSL, and SSH-host paths) rather than using a platform-bound basename, and the Windows and WSL bucket forms are covered by unit tests, but neither platform was exercised by hand. Mobile is verified by typecheck and unit tests, not on a device or simulator.

Review

  • Cross-platform: the seed scan reuses the same bucket-name encoder the AI Vault session scanner uses, rather than a second approximation of it. The first draft of this PR collapsed runs of non-alphanumerics while the real encoder emits one dash per character, which silently matched nothing for any dot-path root and nothing at all on Windows, where the default workspace root starts C:\. Now shared, with the sibling-prefix boundary check that stops …/orca from absorbing …/orca-secret.
  • Remote SSH: both remote creation paths retire names. The backfill scan is local and best-effort by design — agent state for an SSH workspace lives on the execution host, so names spent only there stay issuable until this host observes them. Documented in the module.
  • Mobile: covered in this PR. Mobile previously hand-duplicated the desktop algorithm and deduped only against live workspaces; both now call one shared selector.
  • Folder workspaces: correctly untouched. createFolderWorkspace never derives a path from the name (the path is the folder; the name only becomes displayName), so there is no directory to collide and nothing to retire.
  • First-work folder rename: covered, and this is likely the most common trigger. renameWorktreeFolderOnFirstWork moves a creature-named folder to a work-derived name, which frees the creature name back into the pool while the agent history for the old path stays on disk. Recording at creation covers this; deriving the used-set from live worktrees never could.

Known gaps

  • The seed scan does not cover Codex. Codex records the workspace cwd inside ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl rather than in a directory name, so there is nothing to read from directory listings, and parsing user conversation files to seed a name registry is not a trade this feature justifies. Names spent only under Codex before this change stay issuable. Every name spent after it is recorded at create time regardless of which agent runs there, so this is a one-time seeding gap, not an ongoing one.
  • Names spent only on an SSH host stay issuable until this host observes them, since the backfill scan is local.
  • Repo remove/re-add on an SSH host loses its retirements. A local repo re-seeds from the backfill scan on re-add; an SSH repo cannot, because the scan only sees this machine. Noted in the module.
  • Growth: bounded per repo by a named cap set well above the 552-name pool. A cap inside the pool would start handing back names whose agent state is still on disk, so the bound only ever bites on -2/-3 tier accumulation.
  • Backwards compatibility: the persisted key is optional and round-trips through the existing load spread; a corrupt or missing map degrades to "nothing retired". The new request method is additive, returns only the selected collision domain, and older hosts reject it cleanly; every client catches that unsupported-method response and falls back to live-only dedupe, which is pinned by a test. nameWasGenerated is a new optional create param whose absence means "user-typed", which is the pre-retirement behavior, so an older client talking to a newer host simply gets no retirement. No stream opcode or existing response shape changed. The feature is unreleased, and the storage key is unchanged from the first revision of this PR, so no migration is needed.
  • Performance: two directory reads, once per cwd namespace per app run. Deriving a namespace runs computeWorktreePath, which for a WSL repo makes a blocking wsl.exe call whose failure path is uncached upstream, so the key is memoized and the peer scan is lazy — a repo's own retirements never touch a path, and a peer's namespace is derived only once that peer is known to hold retirements. The whole path is also gated on nameWasGenerated, so CLI and automation creates never reach it.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Generated workspace names were deduped only against currently-live
worktrees, so deleting a workspace returned its name to the pool. A later
workspace could draw the same name, land on the same directory path, and
inherit the previous occupant's agent conversation history — coding-agent
CLIs key their prompt history and transcripts by cwd.

Names are now retired permanently per repo. The registry is written in
main with the name Git actually used (the create loop can advance past a
requested name on collision), and seeded once per run from workspace
directories and surviving agent transcript buckets so already-spent names
are excluded from the start. Suggestions degrade to -2, -3 variants
instead of recycling, and those variants retire too.

User-typed names are untouched: retirement filters suggestions only.
@coderabbitai

coderabbitai Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds shared worktree-name normalization and selection utilities with cross-platform path handling. It discovers and persists retired generated names by workspace key, backfills them from workspace and Claude project paths, and exposes repository-scoped lookup through runtime, RPC, IPC, preload, and web APIs. Worktree creation skips retired names for generated requests and records successful generated names. Mobile and renderer clients load retired names and include generated-name provenance in creation requests.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary change: preventing reuse of generated workspace names.
Description check ✅ Passed The description covers the required sections with detailed rationale, implementation scope, testing, visual proof, review considerations, and known gaps.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch brennanb2025/retire-generated-workspace-names

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Mobile hand-duplicated the desktop name-suggestion algorithm and deduped
only against live workspaces, so a phone could still be offered a name
whose deleted workspace left agent conversation state behind at that path.

Both platforms now call one shared selector in src/shared, so the two can
no longer drift. The host publishes retired names as an optional field on
the existing worktree.list response, and mobile fetches them per selected
repo while the create sheet is open — mirroring the desktop hook.

Mobile never calls worktree.list for its catalog (it uses worktree.ps,
which carries rows only), so this is a targeted request rather than a
change to the catalog or its cache. Hosts predating the field omit it and
mobile falls back to live-only dedupe, which is the pre-change behavior.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/shared/worktree-name-suggestion.ts (2)

17-26: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a cross-platform path utility.

stripTrailingSeparators and suggestionPathBasename parse / and \ directly. Use a cross-platform path helper that is available in every desktop and mobile bundle. Retain the POSIX and Windows fixture coverage.

Verify bundle compatibility before selecting the utility. As per coding guidelines, “Use path.join or Electron/Node path utilities for file paths; never assume / or \.”

Source: Coding guidelines


3-11: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the API comments.

These blocks repeat implementation and product history. Keep only the non-obvious contract, such as requiring usedNames to include retired names. As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”

Also applies to: 33-39

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 67a4b322-f227-43b2-8f76-38d1858e29af

📥 Commits

Reviewing files that changed from the base of the PR and between 3290ca0 and 59f1105.

📒 Files selected for processing (23)
  • mobile/src/components/NewWorktreeModal.tsx
  • mobile/src/components/worktree-name-suggestion.test.ts
  • mobile/src/components/worktree-name-suggestion.ts
  • mobile/src/worktree/use-retired-worktree-names.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees.ts
  • src/main/persistence-worktree-name-retirement.test.ts
  • src/main/persistence.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/worktree-name-retirement.test.ts
  • src/main/worktree-name-retirement.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts
  • src/renderer/src/components/sidebar/worktree-name-suggestions.ts
  • src/renderer/src/hooks/useComposerState.ts
  • src/renderer/src/hooks/useRetiredWorktreeNames.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/constants.ts
  • src/shared/runtime-types.ts
  • src/shared/types.ts
  • src/shared/worktree-name-suggestion.test.ts
  • src/shared/worktree-name-suggestion.ts

Comment thread src/main/ipc/worktrees.ts Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
@brennanb2025
brennanb2025 force-pushed the brennanb2025/retire-generated-workspace-names branch from 0c13871 to 21a117a Compare August 13, 2026 22:06
@brennanb2025

Copy link
Copy Markdown
Contributor Author

STA-4189 validation evidence (PR #14350, 21a117aa34)

Validation-only run in isolated Electron user data against this worktree. No merge/push/commit from this pass.

Identity

window.api.app.getIdentity():

  • name: Orca: brennanb2025/retire-generated-workspace-names
  • devLabel: danio @ brennanb2025/retire-generated-workspace-names
  • devBranch: brennanb2025/retire-generated-workspace-names
  • devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/danio
  • isDev: true
  • CDP: 127.0.0.1:9339 renderer http://127.0.0.1:5174/

Desktop (isolated disposable repo)

  • Opened the real Create worktree composer (name field left blank so the generated creature name is used).
  • First create produced a normal-looking name: arowana.
  • Deleted that workspace. Host registry still listed arowana.
  • Second create produced porcupinefish, not arowana. Registry then: ["arowana","porcupinefish"].
  • Generated names look like the existing marine-creature pool (no suffix/token).

03-create-composer-open.png

04-created-workspace-arowana.png

07-created-workspace-porcupinefish.png

Create gating while retired names load: create is enabled after the list returns. A runtime delay stub on listRetiredNames did not keep the composer button disabled (composer hook likely kept a matching loaded cache). Code still gates submit / createDisabled on retiredWorktreeNamesLoading; the disabled frame was too short to capture visually in this isolated profile.

Mobile (iOS Simulator)

  • Platform: iOS Simulator, iPhone 17 Pro, iOS 26.5 (50FD514C-96F6-446E-AC90-D07A24CAB3A0)
  • Metro: Orca terminal Mobile QA STA-4189 on LAN port 8088 (8081/8082 already taken)
  • App loaded as Orca Mobile (not Expo launcher / redbox)
  • Driven only with orca emulator (tap/gesture/ax). Computer Use used only for Simulator screenshots.
  • Opened Create Workspace on already-paired Host 54 / scratch-repo. Did not create a workspace on that host (user desktop, not the isolated PR profile).
  • Isolated Electron instance was not paired to the simulator, so spent-name reuse could not be proven on mobile.

06-mobile-create-sheet.png

11-mobile-after-create-sheet.png

Logs

  • Renderer: no retirement/listRetiredNames errors. Unrelated: Linear keychain decrypt (userCanceledErr / isolated profile), tooltip controlled/uncontrolled, React Grab outdated.
  • Main: same Linear keychain errors; [orchestration] terminal_liveness_unavailable on empty isolated profile; Claude usage 429.
  • Metro: bundle served; later host WS reconnects (Connection refused) to existing paired hosts. No redbox.

Gaps

  • Visual create-button disabled state while retired names load was not captured.
  • Mobile create-sheet opened, but spent-name reuse was not exercised on-device (would require pairing the isolated PR host or creating on the user’s Host 54).
  • Android not run (adb missing).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 06b1dd9b-3764-493b-a11a-b5b776c625ca

📥 Commits

Reviewing files that changed from the base of the PR and between 59f1105 and ba024d5.

📒 Files selected for processing (16)
  • mobile/src/components/NewWorktreeModal.tsx
  • mobile/src/worktree/use-retired-worktree-names.ts
  • src/main/ipc/worktrees-windows.test.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/persistence-worktree-name-retirement.test.ts
  • src/main/persistence.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/worktree.test.ts
  • src/main/runtime/rpc/methods/worktree.ts
  • src/main/runtime/runtime-rpc.ts
  • src/main/worktree-name-retirement.test.ts
  • src/main/worktree-name-retirement.ts
  • src/renderer/src/hooks/useComposerState.ts
  • src/renderer/src/hooks/useRetiredWorktreeNames.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/main/persistence.ts
  • mobile/src/components/NewWorktreeModal.tsx
  • src/main/runtime/orca-runtime.ts
  • src/main/ipc/worktrees.ts
  • src/renderer/src/hooks/useComposerState.ts

Comment thread src/main/runtime/orca-runtime.test.ts Resolved
Comment thread src/main/worktree-name-retirement.ts Resolved
@brennanb2025

brennanb2025 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor Author

[!WARNING]

Superseded validation: this local-layout proof passed, but SSH validation at the same head found repo-qualified generated names were not persisted as retired. Do not treat this comment as landing approval; a fix and fresh exact-head rerun are in progress.

Exact-final-head validation (PR #14350, ba024d52bf)

Validation-only run in an isolated Electron user-data dir against this worktree. No merge/push/commit. Screenshots are attachments only.

Identity

window.api.app.getIdentity():

  • name: Orca: brennanb2025/retire-generated-workspace-names
  • devLabel: danio @ brennanb2025/retire-generated-workspace-names
  • devBranch: brennanb2025/retire-generated-workspace-names
  • devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/danio
  • isDev: true
  • CDP: 127.0.0.1:9334 renderer http://127.0.0.1:5177/

Desktop (isolated disposable repo)

  • Opened the real Create worktree composer with the name field left blank so the generated creature name is used.
  • First create produced devilray. Host registry: ["devilray"].
  • Deleted that workspace. Registry still listed devilray.
  • Second create produced grayling, not devilray. Registry then: ["devilray","grayling"].
  • Generated names look like the existing marine-creature pool (no suffix/token). Deleted name remained retired and was not reissued.

02-create-composer-open.png

03-created-workspace-devilray.png

04-after-delete-devilray-retired.png

06-created-workspace-grayling.png

Narrow mobile RPC contract (runtime, isolated host)

Invoked worktree.listRetiredNames on this exact-head runtime over the isolated Unix socket:

  • ok: true
  • result keys: only retiredNamesByRepo (no worktrees listing)
  • value for the disposable repo: ["devilray","grayling"]

That is the dedicated method mobile now calls instead of piggybacking on worktree.list.

Mobile UI (optional, already-booted simulator)

  • Platform: iOS Simulator, iPhone 17 Pro, iOS 26.5 (50FD514C-96F6-446E-AC90-D07A24CAB3A0)
  • Driven only with orca emulator. Screenshot via simctl io (no Computer Use interaction).
  • Opened Create Workspace on already-paired Host 54 / scratch-repo. Did not create a workspace on that host.
  • Isolated Electron instance was not paired to the simulator, so spent-name reuse could not be proven on mobile.

07-mobile-create-sheet.png

Verdict

Pass on desktop generated-name create/delete/create and on the isolated-host worktree.listRetiredNames contract.

Gaps: mobile reuse against this exact head was not exercised (would require pairing the already-attached user host to the isolated profile). Delete used removeWorktree(..., force=true) to skip the native confirm dialog. Isolated-profile Keychain/Linear decrypt errors and a grayling startup-terminal selector_not_found were unrelated to retirement.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d1118d46-84e4-4158-938c-91a492bf1d2d

📥 Commits

Reviewing files that changed from the base of the PR and between b15c7e0 and 3b082a9.

📒 Files selected for processing (5)
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees-windows.test.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/runtime/orca-runtime.ts
  • src/main/ipc/worktrees-windows.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/ipc/worktrees.test.ts

Comment thread src/main/ipc/worktree-remote.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Exact final head 3b082a9470

Validation-only run in an isolated Electron user-data dir against this worktree. No source edits, merge, push, or commit. Screenshots are attachments only.

Identity

window.api.app.getIdentity() plus git rev-parse HEAD:

  • name: Orca: brennanb2025/retire-generated-workspace-names
  • devLabel: danio @ brennanb2025/retire-generated-workspace-names
  • devBranch: brennanb2025/retire-generated-workspace-names
  • devWorktreeName: danio
  • devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/danio
  • isDev: true
  • HEAD: 3b082a94709e1693bbf9ed164aa95eb80502ca75
  • CDP: 127.0.0.1:9345 renderer http://127.0.0.1:5184/

Desktop (isolated disposable repo pr14350-final-scratch)

  • Opened the real Create worktree composer with the name field left blank so the generated creature name is used.
  • First create produced porcupinefish. Host registry: ["porcupinefish"].
  • Deleted that workspace. Registry still listed porcupinefish. Sidebar returned to main only.
  • Second create produced tiamat, not porcupinefish. Registry then: ["porcupinefish","tiamat"].
  • Stale-client guard: requested the retired generated name porcupinefish again via authoritative worktrees.create. Host advanced to canonical suffix porcupinefish-2 at a new path (.../porcupinefish-2), and did not reuse the retired cwd (.../porcupinefish). Registry then: ["porcupinefish","tiamat","porcupinefish-2"].

02-create-composer-blank.png

03-created-first-workspace.png

04-after-delete-first-retired.png

05-create-composer-after-delete.png

06-created-second-workspace.png

07-stale-client-suffix.png

Mobile UI (optional)

orca emulator list reported running: false. Task allowed reuse of an already-running iOS simulator only, so no simulator was booted and no create was performed on the user's real paired host. Mobile create-sheet render was skipped.

Verdict

Pass on desktop blank-name create/delete/create (first name stayed retired) and on the authoritative stale-client suffix (porcupinefish → porcupinefish-2).

Gaps: mobile reuse against this exact head was not exercised (no already-running simulator). Delete used removeWorktree(..., force=true) to skip the native confirm dialog. Isolated-profile Keychain/Linear decrypt errors and startup-terminal selector_not_found on generated workspaces were unrelated to retirement.

The bucket-name encoder and its scope-boundary check were private to the
session scanner, so a second consumer had to reimplement them — and got the
per-character encoding wrong. Move both to a shared module with direct tests.
The bucket encoder collapsed runs of non-alphanumerics while the real one
emits a dash per character, so every dot-path bucket missed and the Windows
default workspace root (C:\...) matched nothing at all. Reuse the shared
encoder and its boundary check, which also stops a repo absorbing a sibling
whose path merely shares its prefix.

Also:
- Derive the workspace leaf by stripping the known encoded parent instead of
  guessing from trailing dash segments, which retired the parent directory's
  name whenever a workspace was named numerically.
- Reuse isAutoGeneratedCreatureBranchName so the -10 and -100 tiers retire.
- Drop the .codex/sessions root: Codex keeps the cwd inside the transcript
  rather than in a directory name, so the scan could only ever see a year
  folder. Reading transcript contents is not a trade this feature justifies,
  so the gap is documented instead.
- Honor CLAUDE_CONFIG_DIR, which relocates the bucket root.
- Delete the unused retirableLeafName export.

Tests write buckets with the real per-character encoding against a fake home,
covering POSIX, dot-directory, Windows drive and WSL UNC roots; all three
platform cases fail against the previous encoder.
Two problems in the host-side registry.

Retirement fired for every create, including names the user typed. The
creature pool contains ordinary words — orca, runner, sole, molly, oscar — so
typing a retired 'nautilus' silently produced directory and branch
'nautilus-2' and burned the name for good. Creates now carry an explicit
nameWasGenerated flag; both the skip and the retire are gated on it, and it
defaults to false so CLI and automation callers are unaffected.

The registry was keyed by repo id, but both readers already discarded the id
and unioned by the cwd collision key, because the collision this prevents is
on the path. Keying by that namespace directly fixes several things at once:
entries no longer orphan when a repo is removed, remove/re-add no longer loses
every retirement for an unchanged path, the missing removeProject prune is
moot, and the backfill promise no longer merges into only the first repo id it
saw. The feature is unreleased, so no migration is needed.

Also:
- Memoize the collision key. It runs computeWorktreePath, which for a WSL repo
  is a blocking execFileSync('wsl.exe') whose failure path is uncached, and
  the previous code recomputed it once per repo on every create and every
  listRetiredNames call.
- Drop retiredNamesByRepo from the worktree list result. It had no readers and
  leaked onto 'orca worktree list --json', and its awaited backfill sat on CLI
  selector resolution. The dedicated listRetiredNames RPC keeps its consumers.
- Make the three RuntimeStore methods required. RuntimeStore is file-private
  with two constructors, so the 'older embedders' the optionality protected do
  not exist, and the optional chain silently returned no retirements.
- Revert the unrelated forceDeleteBranch rewrite, and make room under the
  file's line budget by extracting the create-args mapping instead.
Desktop and mobile now mark a create as generated-name only when the user
typed nothing and the composer fell back to the suggestion, so the host knows
which names it may retire.

Remove the retired-names loading gate from every create path. The host already
skips retired candidates before doing any git work, so the client gate bought
nothing while it could disable Create for the length of a full mobile
reconnect ladder (the wait had no timeout) and blank the desktop button
between queued creates. The suggestion still waits; the button never does.

Also make the web client call worktree.listRetiredNames instead of hardcoding
an empty list — the method is registered and mobile-allowlisted, so the
comment claiming no wire call existed was wrong — and filter the mobile
response to strings so a malformed row cannot throw during normalization.
…enerated-workspace-names

# Conflicts:
#	src/renderer/src/store/slices/worktree-helpers.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/main/ai-vault/claude-project-dir-encoding.ts (1)

3-7: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the implementation comments.

Keep the non-obvious NFC and lossy-encoding rationale. Remove repeated encoding details.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”

Also applies to: 14-15, 23-24

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 52c39ac7-5fa8-44c6-9199-fa04250f26ed

📥 Commits

Reviewing files that changed from the base of the PR and between 3b082a9 and ef06e49.

📒 Files selected for processing (37)
  • mobile/src/components/NewWorktreeModal.tsx
  • mobile/src/tasks/blank-workspace-create.test.ts
  • mobile/src/tasks/blank-workspace-create.ts
  • mobile/src/worktree/use-retired-worktree-names.ts
  • src/main/ai-vault/claude-project-dir-encoding.test.ts
  • src/main/ai-vault/claude-project-dir-encoding.ts
  • src/main/ai-vault/session-scanner-scope-discovery.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees-windows.test.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/persistence-worktree-name-retirement.test.ts
  • src/main/persistence.ts
  • src/main/runtime/fit-override-integration.test.ts
  • src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts
  • src/main/runtime/graph-sync-payload-partition.test.ts
  • src/main/runtime/mobile-presence-lock.test.ts
  • src/main/runtime/mobile-subscribe-integration.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/remote-desktop-driver.test.ts
  • src/main/runtime/rpc/methods/worktree-create-args.test.ts
  • src/main/runtime/rpc/methods/worktree-create-args.ts
  • src/main/runtime/rpc/methods/worktree-schemas.ts
  • src/main/runtime/rpc/methods/worktree.ts
  • src/main/runtime/terminal-query-responder.test.ts
  • src/main/worktree-name-retirement.test.ts
  • src/main/worktree-name-retirement.ts
  • src/renderer/src/hooks/useComposerState.ts
  • src/renderer/src/lib/pending-worktree-creation.ts
  • src/renderer/src/lib/worktree-creation-flow.ts
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees.test.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/constants.ts
  • src/shared/types.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/main/persistence.ts
  • src/shared/constants.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/persistence-worktree-name-retirement.test.ts
  • mobile/src/worktree/use-retired-worktree-names.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/ipc/worktrees.ts
  • src/main/ipc/worktrees.test.ts

Comment thread src/main/worktree-name-retirement.ts Resolved
Reverts the collision-key storage key. It was a function of workspaceDir,
nestWorkspaces, worktreeBasePath and repo.path, so toggling any one of those
orphaned every retirement for every affected repo at once — trading a rare
churn (remove/re-add) for a common one. The read path already unions by cwd
namespace at query time, so cross-repo sharing never depended on the storage
key.

Instead, address the growth and orphaning directly:
- Drop the registry in removeProject, and in removeProjectForHost once the last
  host's copy of the repo id is gone, alongside the sparse-preset deletes that
  already follow this convention.
- Bound each repo's registry. The cap sits far above the 552-name pool because
  evicting inside it would reissue a name whose agent state is still on disk;
  only -2/-3 tier accumulation can ever reach it.
- Carry retirements through profile transfer, re-keyed to the destination repo
  id and dropped from the source, mirroring sparsePresetsByRepo.

Separately, fix the backfill merge: the scan promise is cached per cwd
namespace, but it closed over the first repo id that triggered it, so a second
repo in the same namespace received nothing. The scan stays shared; the merge
moves out of the cached promise and runs for whichever repo asked.

Local repos re-seed on re-add through that backfill. SSH repos do not — the
scan cannot see the execution host — which is now stated in the module.
Names the trap directly: the neighbouring 50/200 bounds cap histories, so
lowering this one to match them would silently start reissuing names whose
agent state is still on disk. Also states that oldest-first eviction is a
deliberate least-bad choice rather than a neutral one.
This client hand-enumerates worktree.create params, so the new optional field
was silently dropped and typecheck could not see it. On web and paired-desktop
the host therefore never received it: generated names were never retired, and
the host-side skip that backstops a stale suggestion was disabled too. The same
client does fetch retired names for suggestions, so it was filtering against a
registry nothing ever wrote to.

The test asserts both directions, and fails without the fix.
isAutoGeneratedCreatureBranchName strips exactly one trailing -N, which is
right for auto-rename eligibility but wrong here. Once the pool is spent the
suggester emits nautilus-2, and a collision on that yields nautilus-2-3 —
which a single strip leaves as nautilus-2, not a pool name, so retirement
no-opped at exactly the tier where every base name is already gone. Strip
repeated suffixes locally rather than moving the auto-rename predicate.
The backfill runs on composer repo-select, not just at create time, and it
derived the probe path synchronously — which for a WSL repo with a mirrored
workspace dir reaches getWslHome and its blocking execFileSync('wsl.exe').
A stopped distro froze the main process for up to 5s on composer open.

Adds an async twin of computeWorktreePath and uses it for the probe. Resolving
the home there also warms the shared cache, so later sync callers are free.

Also stops memoizing the collision key when the WSL home is still unresolved:
only the success path is cached upstream, so caching the fallback namespace
would strand the repo there for the rest of the session.
refreshKey changes on every workspace-list mutation, so create-multiple
refetches after each create and the hook returned an empty list until the
refetch landed — precisely the window in which resetForNextCreate clears the
name field and a fresh suggestion is drawn. Keep the previous answer while
revalidating and reset only when the repo changes; a failed refresh keeps what
was already loaded rather than un-retiring everything.

Also makes the returned array referentially stable, so the suggestion memo
downstream stops rerunning on every refetch.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron QA — worktree-name retirement (PR 14350)

Dev build: 58e8c7d4810052e848c6cb3f019e7a88d2015e76
Instance identity: Orca: brennanb2025/pr-14350-electron-qa (isDev: true, repo root /Users/brennanbenson/orca/workspaces/orca/pr-14350-electron-qa)
Surface: isolated user-data profile + throwaway git repo orca-qa-14350-repo.Hw4SJR. QA worktrees were removed after capture.

What I exercised

Opened this PR's Electron dev build over CDP and used the real New Workspace composer plus the worktree create/delete path. Playwright pointer clicks and a live openModal evaluate both wedged the inspector, so create/delete/type were driven through window.api.worktrees.create / removeWorktree (same host retirement logic the composer uses at submit). The composer itself was opened and captured on screen.

The name field does not show a pre-filled creature name. It stays blank with the Smart placeholder; the generated name is chosen at submit time when the field is empty.

Observed

1. Baseline composer. Create worktree dialog opens with an empty name field and an enabled Create worktree button.

07-composer-after-open-os.png

2. No reissue (core fix). Generated create of nautilus produced workspace nautilus. After delete, listRetiredNames returned ["nautilus"]. A second generated create that asked for nautilus produced nautilus-2, not nautilus.

04-sidebar-nautilus.png

05-sidebar-nautilus-2-no-reissue.png

3. Repeat. Same pattern: generated kraken → delete → generated kraken again became kraken-2. Then generated manatee issued as manatee. Sequence of issued names: nautilus, nautilus-2, kraken, kraken-2, manatee. No exact name was handed out twice.

4. User-typed names still work (regression guard). After nautilus was retired, an explicit create with name: "nautilus" and nameWasGenerated: false produced exactly nautilus, not nautilus-3. Visible in the sidebar next to manatee and kraken-2.

06-user-typed-nautilus-exact.png

5. Create-button steadiness. While the composer sat idle, Create worktree stayed enabled (not disabled). A second idle capture looked the same. I could not watch it across a live composer create/delete because CDP died once the composer mounted.

08-composer-idle-create-enabled.png

Landing/context for the isolated instance:

01-landing.png

Could not verify

  • Clicking New workspace / Create worktree / Create inside the composer. Playwright clicks never completed, and openModal left the CDP inspector wedged (the window still painted; this is an automation/inspector deadlock, not proof the UI is frozen for a user).
  • Typing a retired creature name into the composer name field. Same CDP limitation.
  • The pre-create “offered” creature name as a visible string in the name field. The field is blank; the offer happens at submit.
  • Create-button flicker across a composer-driven create or delete cycle.
  • Folder workspaces, SSH/WSL hosts, or a fully exhausted 552-name pool.

Bottom line

On this tree, generated names were not reissued after delete (nautilus → nautilus-2, kraken → kraken-2), and a user-typed retired name came back as the exact name with no suffix. I did not drive those two outcomes through the composer controls, so this is not a full UI-click pass of the New Workspace composer.

…enerated-workspace-names

# Conflicts:
#	src/preload/api-types.ts
#	src/shared/types.ts
…ation

The desktop and mobile hooks that fetch retired names had already drifted
four ways. The transports genuinely differ (IPC vs RPC), but the caching
rules must not, and mobile's copy reset to [] on any error -- which
un-retires every name for the rest of the sheet session, the one outcome
retirement exists to prevent.

Moves the rules into src/shared/worktree/retired-name-cache: response
normalization, the never-leak-across-repos rule, and the hold-previous-on-
failure rule. Pure, no React, because src/shared is on the main process's
import graph. Each platform keeps its own transport and effect.

Mobile moves up to desktop's behavior: it now holds the previous answer
through a failed refresh, and refetches when the workspace list changes
instead of never refetching after mount.

Also drops the unused `loading` return. Neither platform consumed it; its
only consumer was the Create-button gate reviewed out earlier, and removing
it makes that regression unexpressible.
Main dropped the src/shared/types barrel, so the retirement module's import
resolved locally but not against the PR's merge base.
…enerated-workspace-names

# Conflicts:
#	src/main/runtime/rpc/methods/worktree.ts
… not eviction

Retirement is a correctness guarantee — a spent name's directory may still hold
agent conversation state keyed by that cwd — so the 2000-entry cap was the wrong
shape: reaching it handed a name back. At the owner's measured rate (~6.6 pool
names retired per day in one repo) the cap was ~9 months out.

Names come from a fixed 552-entry pool and the suggester only reaches tier N+1
once every tier-N name is taken, so a completed tier is exactly a set that no
longer needs listing. A row is now a watermark plus the names above it: reads
answer at-or-below the watermark with no lookup, and compaction drops the 552
entries the watermark now covers. Bounded at one pool per repo forever, with no
eviction and nothing un-retired.

Tiers can complete out of order (a create-time collision can spend `nautilus-2`
while tier 1 is open), so compaction loops and higher-tier names simply wait.

The RPC result carries the watermark beside the names as a new field; a client
predating it reads the names only and under-retires the compacted tiers, which
degrades to the pre-retirement behavior rather than breaking.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Desktop validation (PR commit 5c51039c0d45625e3eb7387ec753707142c2ba36)

Isolated Electron session on CDP 9342 / renderer 5177, unique ORCA_DEV_USER_DATA_PATH. window.api.app.getIdentity().devRepoRoot = /Users/brennanbenson/orca/workspaces/orca/danio. Exercised on a disposable git repo via the real Create/Delete workspace UI (Playwright CDP only).

Generated names are retired

  1. Empty-name create produced porgy and immediately retired it (listRetiredNames = ["porgy"]).
  2. Deleted porgy through the workspace context menu + Delete Workspace dialog.
  3. Next empty-name create produced conch, not porgy. Registry: ["porgy","conch"].

First generated workspace: porgy

Delete confirm for porgy

Next generated workspace is conch, not porgy

Typed names remain reusable

Typed qa-manual-reuse, created, deleted, typed the same name again, and created successfully. Registry stayed ["porgy","conch","sardine"] (sardine was an extra generated create during the run) and never included qa-manual-reuse.

Typed name before first create

Same typed name after delete

Recreated typed name

Logs / leftover

Renderer: 0 console errors. App log noise was isolated-profile Keychain/Linear decrypt failures and expected worktree-purge after each delete — none related to name retirement. Test workspaces and the isolated session were cleaned up.

@OrcaWin

OrcaWin commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator

Windows QA @ 440419b (review-only)

Confirmed HEAD 440419bf461a454f098a299cf3565a5ae639ea8d in pr-14350-windows-qa. Focused Windows/WSL retirement + create tests 139 passed; typecheck:node passed. Isolated Electron profile + Playwright CDP only.

Flow: empty-name create → shrimp → delete → next empty-name create → brill (not reused). Registry after delete still had shrimp; after second create: ["shrimp","brill"].

WSL: added \\wsl.localhost\Ubuntu\tmp\orca-qa-14350-TuVNlH. listRetiredNames 12ms/1ms/0ms. Composer open 1136ms, project switch 1387ms. No 5s main-thread freeze.

gh image had no browser session; gh attach has no windows-amd64 binary. Screenshots uploaded to refs/uploads/issues/14350 (not on any branch).

Isolated empty app Composer (empty generated name)
01-isolated-empty.png 03-composer-empty-name.png
First generated create: shrimp After delete: shrimp gone
04-creating-shrimp.png 06-shrimp-deleted.png
Next generated create: brill, not shrimp WSL composer, no hang
08-creating-brill-not-shrimp.png 10-wsl-composer-no-hang.png

…enerated-workspace-names

# Conflicts:
#	src/renderer/src/store/slices/worktrees.ts
@brennanb2025
brennanb2025 merged commit ab9d1a2 into main Aug 15, 2026
45 checks passed
brennanb2025 added a commit that referenced this pull request Aug 16, 2026
…e lane went silent

STA-4471 is now proven: restoring the #14350 gate as a mutation turns four tests
RED across the runtime, SSH and local create paths. fix-4472-4473 typechecks and
its 63 tests pass at head, so the torn-write warning applies to its intermediate
commits but not to its final state.
brennanb2025 added a commit that referenced this pull request Aug 23, 2026
… (STA-4471)

#14350 gated the whole of generated-name retirement on the new optional
`nameWasGenerated` bit, conflating two decisions that pull in opposite
directions:

  - *Which cwd a create may land on* genuinely belongs to the client. A
    generated name is one of ours — nothing was chosen — so folding it onto the
    canonical tier ladder and stepping over cwds this host already spent costs
    the user nothing. A name the user typed is a request; `nautilus` stays
    `nautilus` even where that cwd is retired, because silently handing back
    `nautilus-2` is the worse surprise. This half stays gated, and clients that
    predate the bit are read as typing users, exactly as before #14350.

  - *Whether the created name is recorded as spent* never belonged to the
    client. An older paired or mobile client omits the bit but still hands back
    pool-shaped names, and a registry that never learns about them lets the very
    next generated create collide with one. Recording is only ever a write —
    `addRetiredWorktreeName` self-gates on pool shape, so a coined name like
    `fix-login` is never recorded, and no recorded name ever redirects a typed
    one.

The three create paths — `OrcaRuntimeService.createManagedWorktree` (runtime,
mobile, CLI), `createRemoteWorktree` (SSH) and `createLocalWorktree` (desktop
IPC) — each carried their own copy of the gate plus candidate selection, which
is how one rule ended up applied inconsistently. They now share
`planWorktreeCreateNames`, which is unit-tested directly.

No wire change: no new field, no new opcode, nothing removed from what the host
publishes. A name outside the creature pool never loads the registry, and
neither does a typed name, so neither pays for the deadline-less backfill scan.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(worktree): never reissue a generated workspace name

Generated workspace names were deduped only against currently-live
worktrees, so deleting a workspace returned its name to the pool. A later
workspace could draw the same name, land on the same directory path, and
inherit the previous occupant's agent conversation history — coding-agent
CLIs key their prompt history and transcripts by cwd.

Names are now retired permanently per repo. The registry is written in
main with the name Git actually used (the create loop can advance past a
requested name on collision), and seeded once per run from workspace
directories and surviving agent transcript buckets so already-spent names
are excluded from the start. Suggestions degrade to -2, -3 variants
instead of recycling, and those variants retire too.

User-typed names are untouched: retirement filters suggestions only.

* fix(mobile): honor retired workspace names, on one shared implementation

Mobile hand-duplicated the desktop name-suggestion algorithm and deduped
only against live workspaces, so a phone could still be offered a name
whose deleted workspace left agent conversation state behind at that path.

Both platforms now call one shared selector in src/shared, so the two can
no longer drift. The host publishes retired names as an optional field on
the existing worktree.list response, and mobile fetches them per selected
repo while the create sheet is open — mirroring the desktop hook.

Mobile never calls worktree.list for its catalog (it uses worktree.ps,
which carries rows only), so this is a targeted request rather than a
change to the catalog or its cache. Hosts predating the field omit it and
mobile falls back to live-only dedupe, which is the pre-change behavior.

* fix(worktree): close retirement consistency gaps

* test(worktree): cover retirement runtime contracts

* fix(worktree): retire generated collision names

* fix(worktree): enforce retired names at creation

* refactor(ai-vault): extract the Claude project-dir encoder

The bucket-name encoder and its scope-boundary check were private to the
session scanner, so a second consumer had to reimplement them — and got the
per-character encoding wrong. Move both to a shared module with direct tests.

* fix(worktree): make the retirement seed scan actually match buckets

The bucket encoder collapsed runs of non-alphanumerics while the real one
emits a dash per character, so every dot-path bucket missed and the Windows
default workspace root (C:\...) matched nothing at all. Reuse the shared
encoder and its boundary check, which also stops a repo absorbing a sibling
whose path merely shares its prefix.

Also:
- Derive the workspace leaf by stripping the known encoded parent instead of
  guessing from trailing dash segments, which retired the parent directory's
  name whenever a workspace was named numerically.
- Reuse isAutoGeneratedCreatureBranchName so the -10 and -100 tiers retire.
- Drop the .codex/sessions root: Codex keeps the cwd inside the transcript
  rather than in a directory name, so the scan could only ever see a year
  folder. Reading transcript contents is not a trade this feature justifies,
  so the gap is documented instead.
- Honor CLAUDE_CONFIG_DIR, which relocates the bucket root.
- Delete the unused retirableLeafName export.

Tests write buckets with the real per-character encoding against a fake home,
covering POSIX, dot-directory, Windows drive and WSL UNC roots; all three
platform cases fail against the previous encoder.

* fix(worktree): retire only generated names, keyed by cwd namespace

Two problems in the host-side registry.

Retirement fired for every create, including names the user typed. The
creature pool contains ordinary words — orca, runner, sole, molly, oscar — so
typing a retired 'nautilus' silently produced directory and branch
'nautilus-2' and burned the name for good. Creates now carry an explicit
nameWasGenerated flag; both the skip and the retire are gated on it, and it
defaults to false so CLI and automation callers are unaffected.

The registry was keyed by repo id, but both readers already discarded the id
and unioned by the cwd collision key, because the collision this prevents is
on the path. Keying by that namespace directly fixes several things at once:
entries no longer orphan when a repo is removed, remove/re-add no longer loses
every retirement for an unchanged path, the missing removeProject prune is
moot, and the backfill promise no longer merges into only the first repo id it
saw. The feature is unreleased, so no migration is needed.

Also:
- Memoize the collision key. It runs computeWorktreePath, which for a WSL repo
  is a blocking execFileSync('wsl.exe') whose failure path is uncached, and
  the previous code recomputed it once per repo on every create and every
  listRetiredNames call.
- Drop retiredNamesByRepo from the worktree list result. It had no readers and
  leaked onto 'orca worktree list --json', and its awaited backfill sat on CLI
  selector resolution. The dedicated listRetiredNames RPC keeps its consumers.
- Make the three RuntimeStore methods required. RuntimeStore is file-private
  with two constructors, so the 'older embedders' the optionality protected do
  not exist, and the optional chain silently returned no retirements.
- Revert the unrelated forceDeleteBranch rewrite, and make room under the
  file's line budget by extracting the create-args mapping instead.

* fix(worktree): send name provenance and stop gating Create on the fetch

Desktop and mobile now mark a create as generated-name only when the user
typed nothing and the composer fell back to the suggestion, so the host knows
which names it may retire.

Remove the retired-names loading gate from every create path. The host already
skips retired candidates before doing any git work, so the client gate bought
nothing while it could disable Create for the length of a full mobile
reconnect ladder (the wait had no timeout) and blank the desktop button
between queued creates. The suggestion still waits; the button never does.

Also make the web client call worktree.listRetiredNames instead of hardcoding
an empty list — the method is registered and mobile-allowlisted, so the
comment claiming no wire call existed was wrong — and filter the mobile
response to strings so a malformed row cannot throw during normalization.

* fix(worktree): key retirement by repo id and prune it with the repo

Reverts the collision-key storage key. It was a function of workspaceDir,
nestWorkspaces, worktreeBasePath and repo.path, so toggling any one of those
orphaned every retirement for every affected repo at once — trading a rare
churn (remove/re-add) for a common one. The read path already unions by cwd
namespace at query time, so cross-repo sharing never depended on the storage
key.

Instead, address the growth and orphaning directly:
- Drop the registry in removeProject, and in removeProjectForHost once the last
  host's copy of the repo id is gone, alongside the sparse-preset deletes that
  already follow this convention.
- Bound each repo's registry. The cap sits far above the 552-name pool because
  evicting inside it would reissue a name whose agent state is still on disk;
  only -2/-3 tier accumulation can ever reach it.
- Carry retirements through profile transfer, re-keyed to the destination repo
  id and dropped from the source, mirroring sparsePresetsByRepo.

Separately, fix the backfill merge: the scan promise is cached per cwd
namespace, but it closed over the first repo id that triggered it, so a second
repo in the same namespace received nothing. The scan stays shared; the merge
moves out of the cached promise and runs for whichever repo asked.

Local repos re-seed on re-add through that backfill. SSH repos do not — the
scan cannot see the execution host — which is now stated in the module.

* docs(worktree): spell out why the retirement bound sits above the pool

Names the trap directly: the neighbouring 50/200 bounds cap histories, so
lowering this one to match them would silently start reissuing names whose
agent state is still on disk. Also states that oldest-first eviction is a
deliberate least-bad choice rather than a neutral one.

* fix(worktree): send name provenance from the web runtime client

This client hand-enumerates worktree.create params, so the new optional field
was silently dropped and typecheck could not see it. On web and paired-desktop
the host therefore never received it: generated names were never retired, and
the host-side skip that backstops a stale suggestion was disabled too. The same
client does fetch retired names for suggestions, so it was filtering against a
registry nothing ever wrote to.

The test asserts both directions, and fails without the fix.

* fix(worktree): retire names that took more than one collision suffix

isAutoGeneratedCreatureBranchName strips exactly one trailing -N, which is
right for auto-rename eligibility but wrong here. Once the pool is spent the
suggester emits nautilus-2, and a collision on that yields nautilus-2-3 —
which a single strip leaves as nautilus-2, not a pool name, so retirement
no-opped at exactly the tier where every base name is already gone. Strip
repeated suffixes locally rather than moving the auto-rename predicate.

* perf(worktree): keep the retirement backfill off the blocking WSL probe

The backfill runs on composer repo-select, not just at create time, and it
derived the probe path synchronously — which for a WSL repo with a mirrored
workspace dir reaches getWslHome and its blocking execFileSync('wsl.exe').
A stopped distro froze the main process for up to 5s on composer open.

Adds an async twin of computeWorktreePath and uses it for the probe. Resolving
the home there also warms the shared cache, so later sync callers are free.

Also stops memoizing the collision key when the WSL home is still unresolved:
only the success path is cached upstream, so caching the fallback namespace
would strand the repo there for the rest of the session.

* fix(worktree): hold retired names across a refresh instead of blanking

refreshKey changes on every workspace-list mutation, so create-multiple
refetches after each create and the hook returned an empty list until the
refetch landed — precisely the window in which resetForNextCreate clears the
name field and a fresh suggestion is drawn. Keep the previous answer while
revalidating and reset only when the repo changes; a failed refresh keeps what
was already loaded rather than un-retiring everything.

Also makes the returned array referentially stable, so the suggestion memo
downstream stops rerunning on every refetch.

* refactor(worktree): put the retired-name cache rules on one implementation

The desktop and mobile hooks that fetch retired names had already drifted
four ways. The transports genuinely differ (IPC vs RPC), but the caching
rules must not, and mobile's copy reset to [] on any error -- which
un-retires every name for the rest of the sheet session, the one outcome
retirement exists to prevent.

Moves the rules into src/shared/worktree/retired-name-cache: response
normalization, the never-leak-across-repos rule, and the hold-previous-on-
failure rule. Pure, no React, because src/shared is on the main process's
import graph. Each platform keeps its own transport and effect.

Mobile moves up to desktop's behavior: it now holds the previous answer
through a failed refresh, and refetches when the workspace list changes
instead of never refetching after mount.

Also drops the unused `loading` return. Neither platform consumed it; its
only consumer was the Create-button gate reviewed out earlier, and removing
it makes that regression unexpressible.

* fix(worktree): import shared types from their real modules

Main dropped the src/shared/types barrel, so the retirement module's import
resolved locally but not against the PR's merge base.

* refactor(worktree): bound the retirement registry by tier compaction, not eviction

Retirement is a correctness guarantee — a spent name's directory may still hold
agent conversation state keyed by that cwd — so the 2000-entry cap was the wrong
shape: reaching it handed a name back. At the owner's measured rate (~6.6 pool
names retired per day in one repo) the cap was ~9 months out.

Names come from a fixed 552-entry pool and the suggester only reaches tier N+1
once every tier-N name is taken, so a completed tier is exactly a set that no
longer needs listing. A row is now a watermark plus the names above it: reads
answer at-or-below the watermark with no lookup, and compaction drops the 552
entries the watermark now covers. Bounded at one pool per repo forever, with no
eviction and nothing un-retired.

Tiers can complete out of order (a create-time collision can spend `nautilus-2`
while tier 1 is open), so compaction loops and higher-tier names simply wait.

The RPC result carries the watermark beside the names as a new field; a client
predating it reads the names only and under-retires the compacted tiers, which
degrades to the pre-retirement behavior rather than breaking.

* fix(worktree): preserve generated name retirement across failures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants